#include "fenimprimerfacture.h"
#include "ui_fenimprimerfacture.h"
#include <QDesktopServices>
#include <QUrl>

FenImprimerFacture::FenImprimerFacture(ListeEleve &listeEleve, Prof ProfConnect, bool ProfConnectEtat, QWidget *parent) :
    QDialog(parent)
{

    setupUi(this);

    m_ListeEleve = &listeEleve;

    m_modelListeEleve = new ListeEleveModel();
    m_modelListeEleve->setListeEleve(*m_ListeEleve);
    m_modelListeEleve->setColumnCheckable(0);

    m_modelSemaine = new QStandardItemModel(this);

    for(int i = 1; i < 7; i++ )
    {
        QStandardItem *item = new QStandardItem(QDate::longDayName(i));
        item->setCheckable(true);
        m_modelSemaine->appendRow(item);
    }

    connect(FacturesParJourRadioButton, SIGNAL(clicked()), this, SLOT(AfficherJourSemaine()));
    connect(FacturesParNomRadioButton, SIGNAL(clicked()), this, SLOT(AfficherListeEleve()));
    connect(ToutesFacturesRadioButton, SIGNAL(clicked()), this, SLOT(AfficherRien()));
    connect(afficherLTatDeLaCotisationCheckBox, SIGNAL(toggled(bool)), this, SLOT(EtatCotisation(bool)));
    connect(imprimerLeDTailDesCoursPrCDentCheckBox, SIGNAL(toggled(bool)), this, SLOT(EtatDetailMoisPrecedents(bool)));
    connect(AnnulerPushButton, SIGNAL(clicked()), this, SLOT(BtnAnnuler()));
    connect(ExportPdfPushButton, SIGNAL(clicked()), this, SLOT(ExportPDF()));
    connect(ExportRtfPushButton, SIGNAL(clicked()), this, SLOT(ExportRTF()));
    connect(ImprimerPushButton, SIGNAL(clicked()), this, SLOT(LancerImpression()));

    ModeImpression = ImpressionFacture::Tout;

    ReceptionListeEleveEtProfConnecte();
}

FenImprimerFacture::~FenImprimerFacture()
{
    delete m_modelListeEleve;

}
void FenImprimerFacture::setEleve(int indexEleve)
{
    m_eleveAImprimer = m_ListeEleve->at(indexEleve);

    QList<QStandardItem *> liste = m_modelListeEleve->findItems(m_eleveAImprimer.getInfo().NomEtPrenom(), Qt::MatchFixedString, 0);

    foreach (QStandardItem * item, liste)
    {
        item->setCheckState(Qt::Checked);
    }
    FacturesParNomRadioButton->setChecked(true);


    AfficherListeEleve();
}

void FenImprimerFacture::ReceptionListeEleveEtProfConnecte()
{

    this->setWindowTitle("Facture " + QString::number(m_ListeEleve->GetAnnee()) +  "-" + QString::number(m_ListeEleve->GetAnnee() + 1));
    factureDuMoisDeLabel->setText("Facture " + QString::number(m_ListeEleve->GetAnnee()) +  "-" + QString::number(m_ListeEleve->GetAnnee() + 1) + " du mois de");
    factureDuMoisDeDateEdit->setDate(QDate::currentDate());
    maListeAImprimer.SetAnnee(m_ListeEleve->GetAnnee());
    for (int i = 0; i < m_ListeEleve->count(); i++)
    {
        maListeAImprimer << m_ListeEleve->at(i);
    }
}
void FenImprimerFacture::ReceptionListeEleveEtProfConnecte(ListeEleve &le, Prof profConnect, bool profConnectEtat, Eleve eleveAImprimer)
{
    ReceptionListeEleveEtProfConnecte();
//    maListeEleve = le;
//    this->setWindowTitle("Facture " + QString::number(maListeEleve.GetAnnee()) +  "-" + QString::number(maListeEleve.GetAnnee() + 1));
//    factureDuMoisDeLabel->setText("Facture " + QString::number(maListeEleve.GetAnnee()) +  "-" + QString::number(maListeEleve.GetAnnee() + 1) + " du mois de");
//    factureDuMoisDeDateEdit->setDate(QDate::currentDate());
//    maListeAImprimer.SetAnnee(maListeEleve.GetAnnee());
//    for (int i = 0; i < maListeEleve.count(); i++)
//    {
//        maListeAImprimer << maListeEleve.at(i);
//    }

    FacturesParNomRadioButton->setChecked(true);

    QList<QStandardItem *> liste = m_modelListeEleve->findItems(eleveAImprimer.getInfo().NomEtPrenom(), Qt::MatchFixedString, 0);

    foreach (QStandardItem * item, liste)
    {
        item->setCheckState(Qt::Checked);
    }
    AfficherListeEleve();
//    for (int i = 0; i < listWidget->count(); i++)
//    {
//        if (eleveAImprimer.getInfo().NomEtPrenom() == listWidget->item(i)->text())
//        {
////            listWidget->item(i)->setCheckState(Qt::Checked);
//            ClicList(listWidget->item(i));
//        }
//    }

}
void FenImprimerFacture::AfficherRien()
{
    listView->setEnabled(false);
    listView->setModel(new QStandardItemModel);
    ModeImpression = ImpressionFacture::Tout;
}
void FenImprimerFacture::AfficherJourSemaine()
{

    listView->setEnabled(true);
    listView->setModel(m_modelSemaine);
    ModeImpression = ImpressionFacture::ParJour;

}
void FenImprimerFacture::AfficherListeEleve()
{
    listView->setEnabled(true);
    listView->setModel(m_modelListeEleve);
    ModeImpression = ImpressionFacture::ParNoms;

}
void FenImprimerFacture::EtatCotisation(bool etat)
{
    Cotisation = afficherLTatDeLaCotisationCheckBox->isChecked();
}
void FenImprimerFacture::EtatDetailMoisPrecedents(bool etat)
{
    DetailMoisPrecedents = imprimerLeDTailDesCoursPrCDentCheckBox->isChecked();
}
ListeEleve FenImprimerFacture::ListeAImprimer()const
{
    ListeEleve le;

    int numRows = 0;
    if (ModeImpression == ImpressionFacture::Tout)
    {
        le = *m_ListeEleve;
    }
    else if (ModeImpression == ImpressionFacture::ParJour)
    {
        numRows = m_modelSemaine->rowCount();
        for(int row = 0; row < numRows; row++)
        {
            if (m_modelSemaine->item(row)->checkState() == Qt::Checked)
            {
                for (int i = 0; i < m_ListeEleve->count();i++)
                    {
                        if (m_ListeEleve->at(i).getCoursParDefaut().getJour() == m_modelSemaine->item(row)->text())
                            le.append(m_ListeEleve->at(i));
                    }
            }
        }
    }
    else if (ModeImpression == ImpressionFacture::ParNoms)
    {
        numRows = m_modelListeEleve->rowCount();
        for(int row = 0; row < numRows; row++)
        {
            if (m_modelListeEleve->item(row)->checkState() == Qt::Checked)
            {
                int index = m_modelListeEleve->item(row)->row();
                le.append(m_ListeEleve->at(index));
            }
        }
        return le;
    }
    return le;
}
void FenImprimerFacture::LancerImpression()
{
    ListeEleve le = ListeAImprimer();
    if (le.count() > 0)
    {
        QPrinter *printer = new QPrinter(QPrinter::HighResolution);
        printer->setPaperSize (QPrinter::A4);
        printer->setOrientation(QPrinter::Portrait);
        printer->setFullPage(true);
        QTextDocument *journal_document = new QTextDocument;
        journal_document->setDefaultFont(QFont("Arial", 6));
        journal_document->setHtml(le.ListeElevePourImpression(factureDuMoisDeDateEdit->date().month(), le.GetAnnee()));
        printer->setOutputFormat(QPrinter::NativeFormat);



//        QTextEdit *texte = new QTextEdit;
//        //texte->setDefaultFont(QFont("Arial", 8));
//        texte->setHtml(maListeAImprimer.ListeElevePourImpression(factureDuMoisDeDateEdit->date().month(), 2011));

//        QTextCursor cursor(texte->textCursor());
//        cursor.movePosition(QTextCursor::Start);

        //QTextTable *table = cursor.insertTable(3, 3);
        //QPrinter Printer(QPrinter::HighResolution);
        //Printer.setPageSize(QPrinter::A4);
        QPrintDialog *dialog = new QPrintDialog(printer, this);
        if (dialog->exec() == QDialog::Accepted)
        {
            journal_document->print(printer);

            //texte->document()->print(&Printer);
            this->close();
        }
    }

}
void FenImprimerFacture::ExportPDF()
{

    ListeEleve le = ListeAImprimer();
    if (le.count() > 0)
    {
        QTextEdit *texte = new QTextEdit;
        texte->setHtml(le.ListeElevePourImpression(factureDuMoisDeDateEdit->date().month(), le.GetAnnee()));

        QTextCursor cursor(texte->textCursor());
        cursor.movePosition(QTextCursor::Start);
        QString fileName = "FactureUnisson-" + QDate::longMonthName(factureDuMoisDeDateEdit->date().month()) + "-" + QString::number(le.GetAnnee()) + ".pdf";
        fileName = QFileDialog::getSaveFileName(this, "Export PDF",
                                                        fileName, "*.pdf");
         if (!fileName.isEmpty()) {
             if (QFileInfo(fileName).suffix().isEmpty())
                 fileName.append(".pdf");
             QPrinter printer(QPrinter::HighResolution);
             printer.setOutputFormat(QPrinter::PdfFormat);
             printer.setOutputFileName(fileName);
             texte->document()->print(&printer);
             this->close();
         }
    }
}
void FenImprimerFacture::ExportRTF()
{
    ListeEleve le = ListeAImprimer();
    if (le.count() > 0)
    {
        QTextEdit *texte = new QTextEdit;
        texte->setText(le.ListeElevePourSauvegardeRTF(factureDuMoisDeDateEdit->date().month(),le.GetAnnee()));

        QTextCursor cursor(texte->textCursor());
        cursor.movePosition(QTextCursor::Start);
        QString fileName = "FactureUnisson-" + QDate::longMonthName(factureDuMoisDeDateEdit->date().month()) + "-" + QString::number(le.GetAnnee()) +  ".rtf";
        fileName = QFileDialog::getSaveFileName(this, "Export TXT",
                                                             fileName, "*.rtf");
         if (!fileName.isEmpty()) {
             if (QFileInfo(fileName).suffix().isEmpty())
                 fileName.append(".html");
             QFile data(fileName);
             if (!data.open(QIODevice::WriteOnly)) {
                 QMessageBox::information(NULL , OUVERTUREFICHIERIMPOSSIBLE, data.errorString());
                 return;
             }

            QTextStream out(&data);

            out << le.ListeElevePourSauvegardeRTF(factureDuMoisDeDateEdit->date().month(),le.GetAnnee());
            this->close();
//            const QString nom = "file:///" + fileName;
//            QDesktopServices::openUrl(QUrl(nom, QUrl::TolerantMode));
         }
    }

}

void FenImprimerFacture::BtnAnnuler()
{
    this->close();
}
//void FenImprimerFacture::ClicList(QListWidgetItem *qItem)
//{
//    switch (ModeImpression)
//    {
//        case 1:
//        if (qItem->checkState() == 2)
//        {
//            for (int i = 0; i < m_ListeEleve->count();i++)
//            {
//                if (m_ListeEleve->at(i).getCoursParDefaut().getJour() == qItem->text())
//                    maListeAImprimer.append(m_ListeEleve->at(i));
//            }

//        }
//        if (qItem->checkState() == 0)
//        {
//            for (int i = (maListeAImprimer.count() - 1); i >= 0 ;i--)
//            {
//                if (maListeAImprimer.at(i).getCoursParDefaut().getJour() == qItem->text())
//                    maListeAImprimer.removeAt(i);
//            }

//        }
//            break;
//        case 2:
//            if (qItem->checkState() == 2)
//            {
//                if (!maListeAImprimer.Existe(qItem->text()))
//                {
//                    Eleve ele = m_ListeEleve->getEleve(qItem->text());
//                    maListeAImprimer.append(ele);
//                }
//            }
//            if (qItem->checkState() == 0)
//            {
//                if (maListeAImprimer.Existe(qItem->text()))
//                    maListeAImprimer.removeAt(maListeAImprimer.getEleveIndex(qItem->text()));
//            }
//            break;
//        default:
//            break;
//    }

//}
